package cn.boat.router.consumer;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ConsumerConnectZookeeper {
    private ZooKeeper zooKeeperConnection ;
    private String IP ;

    public ConsumerConnectZookeeper() {
        GetZookeeperProperties getZookeeperProperties = new GetZookeeperProperties();
        getZookeeperProperties.getPropertiesByName();
        this.IP = getZookeeperProperties.getZookeeperIpPort();
        ZooKeeper zooKeeperConnection =null;
    }


    public ZooKeeper connect() throws Exception {

        CountDownLatch countDownLatch = new CountDownLatch(1);
        Watcher watcher =new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
                    System.out.println("消费者zookeeper连接创建成功！");
                    countDownLatch.countDown();
                }else if (watchedEvent.getState()== Event.KeeperState.Disconnected){
                    System.out.println("消费者zookeeper连接失败");
                }else if (watchedEvent.getState() == Event.KeeperState.Expired){
                    System.out.println("消费者zookeeper会话超时");
                    try {
                        zooKeeperConnection = new ZooKeeper(IP, 20000, this);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        zooKeeperConnection = new ZooKeeper(IP, 20000, watcher);
        countDownLatch.await();
        return zooKeeperConnection;
    }

    public void stopZookeeper() throws InterruptedException {
        zooKeeperConnection.close();
    }

    public ZooKeeper getZooKeeperConnection() {
        return zooKeeperConnection;
    }

    public String getIP() {
        return IP;
    }
}
